package com.chart.web.controller.monitor;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.chart.chart.domian.ChartConfigsUser;
import com.chart.chart.domian.ChartStatistics;
import com.chart.chart.domian.req.PUReq;
import com.chart.chart.domian.req.UListReq;
import com.chart.chart.domian.req.UVipsReq;
import com.chart.chart.domian.resp.PageResp;
import com.chart.chart.domian.resp.UserResp;
import com.chart.chart.domian.vo.ChartConfigsUserVo;
import com.chart.chart.domian.vo.PUVo;
import com.chart.chart.domian.vo.StatisticsVo;
import com.chart.chart.manager.UserStatisticsManager;
import com.chart.chart.service.IChartConfigsUserService;
import com.chart.chart.service.IChartStatisticsService;
import com.chart.common.core.controller.BaseController;
import com.chart.common.core.domain.AjaxResult;
import com.chart.common.core.domain.entity.SysUser;
import com.chart.common.core.domain.entity.UserCoinLog;
import com.chart.common.utils.StringUtils;
import com.chart.common.utils.poi.ExcelUtil;
import com.chart.system.domain.RegistrationChannels;
import com.chart.system.domain.SysUserOrder;
import com.chart.system.domain.vo.SysUserVo;
import com.chart.system.service.ISysUserOrderService;
import com.chart.system.service.ISysUserService;
import com.chart.system.service.IUserCoinLogsService;
import com.chart.system.service.RegistrationChannelsService;
import com.chart.web.controller.chart.dto.ExportDto;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 后台数据统计
 *
 * @author chart
 */
@Api(tags = "后台数据统计模块")
@Validated // 启用参数校验
@RestController
@RequestMapping("/statistics")
public class StatisticsController extends BaseController {


    @Resource
    private UserStatisticsManager userManager;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    RegistrationChannelsService registrationChannelsService;

    @Autowired
    private IChartStatisticsService chartStatisticsService;

    @Autowired
    private IChartConfigsUserService chartConfigsUserService;


    /**
     * 后台管理用户信息查询
     * @param req
     * @return
     */
    @PostMapping("/list")
    public AjaxResult getListBysA(@RequestBody UListReq req) {
        Map<String, Object> data = sysUserService.getList(req);
        return AjaxResult.success(data);
    }



    /**
     * 查询用户保存到我的生成的数量
     *
     * @param req
     * @return
     */
//    @PostMapping("query/chartConfigCount")
//    public AjaxResult querychartConfigCount(@RequestBody UListReq req) {
//        if (ObjectUtils.isEmpty(req)) {
//            logger.warn("req参数为空");
//        }
//        List<ChartConfigsUserVo> chartConfigsUsers = chartConfigsUserService.querychartConfigCount(req);
//        return AjaxResult.success(chartConfigsUsers);
//    }

//    @PostMapping("query/chartConfigCount")
//    public AjaxResult querychartConfigCount(@RequestBody UListReq req) {
//        if (ObjectUtils.isEmpty(req)) {
//            logger.warn("req参数为空");
//        }
//
//        // 处理 startTime 和 endTime 的格式
//        if (req.getStartTime() != null && req.getEndTime() != null && req.getStartTime().equals(req.getEndTime())) {
//            // 将 endTime 设置为当天的 23:59:59
//            LocalDate endDate = LocalDate.parse(req.getEndTime());
//            req.setEndTime(endDate.atTime(23, 59, 59).toString());
//        }
//
//        // 调用 Service 层查询
//        List<ChartConfigsUserVo> chartConfigsUsers = chartConfigsUserService.querychartConfigCount(req);
//        return AjaxResult.success(chartConfigsUsers);
//    }

    @PostMapping("query/chartConfigCount")
    public AjaxResult querychartConfigCount(@RequestBody UListReq req) {
        if (ObjectUtils.isEmpty(req)) {
            logger.warn("req参数为空");
        }

        // 处理空日期情况
        if (req.getStartTime() != null && req.getStartTime().trim().isEmpty()) {
            req.setStartTime(null);  // startTime 为空字符串时设置为 null
        }

        if (req.getEndTime() != null && req.getEndTime().trim().isEmpty()) {
            req.setEndTime(null);  // endTime 为空字符串时设置为 null
        }

        // 调用 Service 层查询
        List<ChartConfigsUserVo> chartConfigsUsers = chartConfigsUserService.querychartConfigCount(req);
        return AjaxResult.success(chartConfigsUsers);
    }


    @ApiOperation("导出图表配置计数")
    @PostMapping("/export/chartConfigCountExport")
    public void chartConfigCountExport(HttpServletResponse response, @RequestBody UListReq req) {
        if (ObjectUtils.isEmpty(req)) {
            logger.warn("req参数为空");
        }
        List<ChartConfigsUserVo> chartConfigsUsers = chartConfigsUserService.querychartConfigCount(req);
        if (StringUtils.isEmpty(chartConfigsUsers)) {
            logger.error("未查询到该列表信息");
        }
        ExcelUtil<ChartConfigsUserVo> util = new ExcelUtil<>(ChartConfigsUserVo.class);
        util.exportExcel(response, chartConfigsUsers, "用户保存管理");
    }


    /**
     * 根据用户id查询照片列表
     *
     * @param
     * @return
     */


    @GetMapping("queryPhotosByUserId")
    public AjaxResult queryPhotosByUserId(@RequestParam @NotNull(message = "userId 不能为空") Long userId) {

        List<ChartConfigsUser> list = chartConfigsUserService.queryPhotosByUserId(userId);
        return AjaxResult.success(list);
    }


    // @PostMapping("query/chartConfigCount")
    public AjaxResult querychartConfigCount2(@RequestBody UListReq req) {

        List<ChartConfigsUserVo> chartConfigsUsers = chartConfigsUserService.querychartConfigCount2(req);

        return AjaxResult.success(chartConfigsUsers);
    }


    @GetMapping("/getSource")
    public AjaxResult getSource() {
        return userManager.getSource();
    }


    @ApiOperation("导出用户数")
    @PostMapping("/exportUser")
    public void export(HttpServletResponse response, @RequestBody UListReq req) {
        if (ObjectUtils.isEmpty(req)) {
            logger.warn("req参数为空");
        }
        List<UserResp> list = userManager.getListBy(req);
        ExcelUtil<UserResp> util = new ExcelUtil<UserResp>(UserResp.class);
        util.exportExcel(response, list, "用户数据");
    }

    @ApiOperation("获取用户PV、UV操作记录")
    @PostMapping("/getPU")
    public AjaxResult getPU(@RequestBody PUReq req) {
        if (ObjectUtils.isEmpty(req)) {
            logger.warn("req参数为空");
        }
        List<PUVo> list = userManager.getPU(req);
        return AjaxResult.success(list);
    }


    @ApiOperation("导出用户PV、UV操作记录")
    @PostMapping("/exportPU")
    public void OpersExport(HttpServletResponse response, @RequestBody PUReq req) {
        if (ObjectUtils.isEmpty(req)) {
            logger.warn("req参数为空");
        }

        List<PUVo> list = userManager.getPU(req);
        ExcelUtil<PUVo> util = new ExcelUtil<PUVo>(PUVo.class);
        util.exportExcel(response, list, "操作数据");
    }

    @ApiOperation("修改用户Vip信息")
    @PostMapping("/addVips")
    public AjaxResult editVips(@RequestBody UVipsReq req) {
        return userManager.editVips(req);
    }


    @ApiOperation("刷新会员信息")
    @GetMapping("/updateVips")
    public AjaxResult updateVips() {
        return userManager.updateVips();
    }


    /**
     * 使用说明点击的操作记录每次点击数据加1
     *
     * @return
     */
    @PostMapping("/operationPv")
    public AjaxResult operationPv() {
        return chartStatisticsService.operationPv();
    }


    //使用说明点击的操作记录查询
    @GetMapping("/operationTotal")
    public AjaxResult operationTotal() {
        return chartStatisticsService.operationTotal();
    }


    @Autowired
    private IUserCoinLogsService userCoinLogsService;

    /**
     * 总登录次数、月登录次数、
     * 付费用户标识（包括vip/智点购买）
     *
     * @return
     */
    @GetMapping("demo")
    public AjaxResult query() {
        List<UserResp> list = userCoinLogsService.querydemo();
        if (list == null) {
            logger.error("未查询到信息");
            return AjaxResult.error("未查询到信息");
        }
        return AjaxResult.success(list);
    }

    /**
     * 查询专家图例列表
     */
    @GetMapping("/queryExpertChart")
    public AjaxResult queryExpertChart() {
        LambdaQueryWrapper<ChartConfigsUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChartConfigsUser::getUserId, 2);
        wrapper.select(ChartConfigsUser::getId, ChartConfigsUser::getChartName, ChartConfigsUser::getImageUrl, ChartConfigsUser::getStatus);
        List<ChartConfigsUser> list = chartConfigsUserService.list(wrapper);
        if (list == null) {
            logger.error("未查询到该列表信息");
            return AjaxResult.error("数据库错误");
        }
        return AjaxResult.success(list);
    }

    /**
     * 修改专家图例
     *
     * @return
     */
    @PostMapping("/updataExpertChart")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult updataExpertChart(@RequestBody ExportDto exportDto) {
        if (exportDto.getId() == null || exportDto.getStatus() == null) {
            logger.warn("修改失败，参数补全status={},id={}",
                    exportDto.getStatus() == null ? "为空" : exportDto.getStatus(),
                    exportDto.getId() == null ? "为空" : exportDto.getId()
            );
            return AjaxResult.error("修改失败，参数补全");
        }
        ChartConfigsUser chartConfigsUser = new ChartConfigsUser();
        chartConfigsUser.setId(exportDto.getId());
        chartConfigsUser.setStatus(exportDto.getStatus());
        try {
            chartConfigsUserService.updateById(chartConfigsUser);
            logger.info("id={}修改专家图例成功", chartConfigsUser.getId());
        } catch (Exception e) {
            logger.warn("id={}修改专家图例失败", chartConfigsUser.getId());
            throw new RuntimeException(e);
        }
        return AjaxResult.success();
    }


}
